package org.lql.algo.codecrush.week008;

import org.lql.algo.common.ListNode;

/**
 * @author: liangqinglong
 * @date: 2025-08-18 23:57
 * @description: 160. 相交链表 <a href="https://leetcode.cn/problems/intersection-of-two-linked-lists/description/">...</a>
 **/
public class GetIntersectionNode {

	public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
		if (headA == null || headB == null) {
			return null;
		}
		ListNode p = headA;
		ListNode q = headB;
		while (p != q) {
			p = p != null ? p.next : headB;
			q = q != null ? q.next : headA;
		}
		return p;
	}

	public static void main(String[] args) {
		GetIntersectionNode getIntersectionNode = new GetIntersectionNode();
		System.out.println(getIntersectionNode.getIntersectionNode(new ListNode(1), new ListNode(2)));
		// listA = [4,1,8,4,5], listB = [5,6,1,8,4,5]
		ListNode headA = new ListNode(4);
		headA.next = new ListNode(1);

		ListNode headB = new ListNode(5);
		headB.next = new ListNode(6);
		headB.next.next = new ListNode(1);

		ListNode common = new ListNode(8);
		common.next = new ListNode(4);
		common.next.next = new ListNode(5);

		headA.next.next = common;
		headB.next.next.next = common;

		System.out.println(getIntersectionNode.getIntersectionNode(headA, headB).val);

	}
}
